//
//  KABSettingVC.m
//  kabu
//
//  Created by XiangDongMBP on 2017/2/12.
//  Copyright © 2017年 East. All rights reserved.
//

#import "KABSettingVC.h"
#import "KABSettingTCell.h"
#import "KABMineSetHeaderHFView.h"
#import "KABRecAddressVC.h"
#import "KABModel.h"
#import "GlobalHeader.h"
#import "KABModifyPwdVC.h"
#import <YYWebImage.h>
#import "MBProgressHUD+XDPrompt.h"
#import "XDAFNetworking.h"
#import "ApiManager.h"
#import "KABRegisterVC.h"

@interface KABSettingVC ()<UITableViewDelegate, UITableViewDataSource, KABSettingTCellDelegate>

@property (weak, nonatomic) IBOutlet UITableView *tableView;
@property (strong, nonatomic) NSArray *sectionTitleArray;
@property (strong, nonatomic) NSArray *generalArray;
@property (strong, nonatomic) NSArray *notifyArray;
@property (strong, nonatomic) NSArray *aboutArray;

//@property (assign, nonatomic) BOOL is_notified; // 是否开启展会开售通知，0-否 1-是
@property (strong, nonatomic) KABMineSettingPushModel *pushModel;   //!< 推送开关的模型
@end

static NSString *const kHeaderViewId = @"KABMineSetHeaderHFView";
static NSString *const kReuseCellId = @"KABSettingTCell";

@implementation KABSettingVC

#pragma mark - life cycle
- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    [self initNavigationBar];
    [self initSubViews];
}

- (BOOL)hidesBottomBarWhenPushed {
    return YES;
}

- (void)initNavigationBar {
    self.navigationItem.title = @"设置";
}

- (void)initSubViews {
    UINib *headerNib = [UINib nibWithNibName:kHeaderViewId bundle:nil];
    [self.tableView registerNib:headerNib forHeaderFooterViewReuseIdentifier:kHeaderViewId];
    UINib *cellNib = [UINib nibWithNibName:kReuseCellId bundle:nil];
    [self.tableView registerNib:cellNib forCellReuseIdentifier:kReuseCellId];
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    
    // 网络请求
    [self requestGetJpushNotify];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}
#pragma mark - UITableViewDataSource
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return self.sectionTitleArray.count;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    if (section == 0) {
        return self.generalArray.count;
    } else if (section == 1) {
        return self.notifyArray.count;
    } else if (section == 2) {
        return self.aboutArray.count;
    } else {
        return 1;
    }
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    KABSettingTCell *cell = [tableView dequeueReusableCellWithIdentifier:kReuseCellId forIndexPath:indexPath];
    if (indexPath.section == 0) {
        cell.leftLabel.text = self.generalArray[indexPath.row];
        cell.leftLabel.textAlignment = NSTextAlignmentLeft;
        cell.msgSwitch.hidden = YES;
        cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
        if ([self.generalArray[indexPath.row] isEqualToString:@"清理缓存"]) {
            YYImageCache *cache = [YYWebImageManager sharedManager].cache;
            [cache.diskCache totalCostWithBlock:^(NSInteger totalCost) {
                dispatch_async(dispatch_get_main_queue(), ^{
                    NSLog(@"字节的数量 = %ld", (long)totalCost);
                    cell.rightLabel.text = [NSString stringWithFormat:@"%ld MB", (long)(totalCost >> 20)];
                });
            }];
        } else if ([self.generalArray[indexPath.row] isEqualToString:@"绑定手机"]) {
            cell.rightLabel.text = [KABModel sharedInstance].userInfo.is_bind_phonenumber ? [KABModel sharedInstance].userInfo.phone_number : nil;
            cell.accessoryType = [KABModel sharedInstance].userInfo.is_bind_phonenumber  ? UITableViewCellAccessoryNone : UITableViewCellAccessoryDisclosureIndicator;
        } else {
            cell.rightLabel.text = nil;
        }
//        if ([self.generalArray[indexPath.row] isEqualToString:@"关注消息是否推送"]) {
//            cell.msgSwitch.hidden = NO;
//            [cell.msgSwitch setOn:self.is_notified animated:NO];
//            cell.accessoryType = UITableViewCellAccessoryNone;
//        }
    } else if (indexPath.section == 1) {
        cell.leftLabel.text = self.notifyArray[indexPath.row];
        cell.leftLabel.textAlignment = NSTextAlignmentLeft;
        cell.rightLabel.text = nil;
        cell.msgSwitch.hidden = NO;
        [cell.msgSwitch setOn:[self.pushModel pushNotifyStateWithIndex:indexPath.row] animated:YES];
        cell.accessoryType = UITableViewCellAccessoryNone;
    } else if (indexPath.section == 2) {
        cell.leftLabel.text = self.aboutArray[indexPath.row];
        cell.leftLabel.textAlignment = NSTextAlignmentLeft;
        cell.rightLabel.text = nil;
        cell.msgSwitch.hidden = YES;
        cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
    } else {
        cell.leftLabel.text = @"退出登录";
        cell.leftLabel.textAlignment = NSTextAlignmentCenter;
        cell.rightLabel.text = nil;
        cell.msgSwitch.hidden = YES;
        cell.accessoryType = UITableViewCellAccessoryNone;
    }
    cell.delegate = self;
    return cell;
}

//- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section {
//    return self.sectionTitleArray[section];
//}

#pragma mark - UITableViewDelegate
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    return 30.0;
}
- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section {
    return 0.1;
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
    KABMineSetHeaderHFView *view = [tableView dequeueReusableHeaderFooterViewWithIdentifier:kHeaderViewId];
    view.titleLabel.text = self.sectionTitleArray[section];
    return view;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    if (indexPath.section == 0) {
        NSString * str = self.generalArray[indexPath.row];
        if ([str isEqualToString:@"收货地址"]) {
            [self jumpToRcvAddress];
        } else if ([str isEqualToString:@"修改密码"]) {
            [self jumpToModifyPwd];
        } else if ([str isEqualToString:@"清理缓存"]) {
            [self clearCache];
        } else if ([str isEqualToString:@"绑定手机"]) {
            [self jumpToBindPhone];
        }
    } else if (indexPath.section == 2) {
        NSString * str = self.aboutArray[indexPath.row];
        if ([str isEqualToString:@"给我评价"]) {
            [self jumpToAppStoreComment];
        }
    } else if(indexPath.section == 3) {
        [self logout];
    }
}

#pragma mark - KABSettingTCellDelegate
- (void)kABSettingTCell:(KABSettingTCell *)cell switchTapped:(UISwitch *)uiswitch {
    NSIndexPath *indexPath = [self.tableView indexPathForCell:cell];
    [self.pushModel setNotifyState:uiswitch.on WithIndex:indexPath.row];
    [self requestSetJpushNotifyWithIndex:indexPath.row is_notified:uiswitch.on];
}

#pragma mark - event response
#pragma mark - private methods
- (void)logout {
    UIAlertController *alertVC = [UIAlertController alertControllerWithTitle:@"确定退出登录？" message:nil preferredStyle:UIAlertControllerStyleActionSheet];
    [alertVC addAction:[UIAlertAction actionWithTitle:@"退出登录" style:UIAlertActionStyleDestructive handler:^(UIAlertAction * _Nonnull action) {
        [[KABModel sharedInstance] logout];
        [[NSNotificationCenter defaultCenter] postNotificationName:KABGlobalNotiLogout object:nil];
    }]];
    [alertVC addAction:[UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleDefault handler:nil]];
    [self presentViewController:alertVC animated:YES completion:nil];
}

- (void)jumpToRcvAddress {
    KABRecAddressVC *vc = [[KABRecAddressVC alloc] init];
    [self.navigationController pushViewController:vc animated:YES];
}
- (void)jumpToBindPhone {
    if ([KABModel sharedInstance].userInfo.is_bind_phonenumber) {
        return;
    }
    
    KABRegisterVC *vc = [[KABRegisterVC alloc] initWithViewType:KABRegisterVCTypeBindPhone];
    vc.completeHandle = ^(NSString *phoneNum) {
        [KABModel sharedInstance].userInfo.is_bind_phonenumber = YES;
        [KABModel sharedInstance].userInfo.phone_number = phoneNum;
        [self refreshWholeView];
    };
    [self showViewController:vc sender:nil];
}
- (void)jumpToModifyPwd {
    KABModifyPwdVC *vc = [[KABModifyPwdVC alloc] init];
    [self showViewController:vc sender:nil];
}

- (void)clearCache {
    MBProgressHUD *hud = [MBProgressHUD xd_showHUDAddedTo:self.view animated:YES];
    hud.mode = MBProgressHUDModeAnnularDeterminate;
    hud.progress = 0;
    hud.label.text = @"清理缓存...";
    
    YYImageCache *cache = [YYWebImageManager sharedManager].cache;
    [cache.diskCache removeAllObjectsWithProgressBlock:^(int removedCount, int totalCount) {
        dispatch_async(dispatch_get_main_queue(), ^{
            hud.progress = (CGFloat)removedCount / (CGFloat)totalCount;
        });
    } endBlock:^(BOOL error) {
        dispatch_async(dispatch_get_main_queue(), ^{
            [hud hideAnimated:YES];
            [self.tableView reloadData];
        });
    }];
}

- (void)jumpToAppStoreComment {
    NSString *str = [NSString stringWithFormat:@"itms-apps://itunes.apple.com/app/id%@", KABGlobalAppStoreId];
    [[UIApplication sharedApplication] openURL:[NSURL URLWithString:str]];
}

- (void)refreshWholeView {
    [self.tableView reloadData];
}

#pragma mark - network request
//- (void)requestSetExhBuyableNoti:(BOOL)is_notified {
//    // 必须要登录
//    if (![KABModel sharedInstance].isLogin) {
//        [[NSNotificationCenter defaultCenter] postNotificationName:KABGlobalNotiUserTokenInvalid object:nil];
//        return;
//    }
//    
//    // 点赞请求
//    NSDictionary *pars = @{@"user_id" : @([KABModel sharedInstance].userInfo.uid),
//                           @"access_token" : [KABModel sharedInstance].userInfo.access_token,
//                           @"is_notified" : (is_notified ? @(1) : @(0))};
//    [[XDAFNetworking sharedInstance] PUT:[ApiManager apiExhibitionBuyableNoti] parameters:pars success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
//        NSLog(@"请求Noti返回：%@", responseObject);
//        if ([responseObject[KABGlobalJsonKeyErrCode] integerValue] == 200) {
//            ;
//        } else {
//            self.is_notified = !is_notified;
//            [self refreshWholeView];
//            [MBProgressHUD showPromptWithAutoHideInView:self.view message:responseObject[KABGlobalJsonKeyMsg]];
//        }
//    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
//        NSLog(@"请求Noti点赞失败：%@", error);
//        self.is_notified = !is_notified;
//        [MBProgressHUD showPromptWithAutoHideInView:self.view message:@"网络请求失败"];
//        [self refreshWholeView];
//    }];
//}
//
//- (void)requestGetExhBuyableNoti {
//    // 必须要登录
//    if (![KABModel sharedInstance].isLogin) {
//        [[NSNotificationCenter defaultCenter] postNotificationName:KABGlobalNotiUserTokenInvalid object:nil];
//        return;
//    }
//    
//    // 点赞请求
//    NSDictionary *pars = @{@"user_id" : @([KABModel sharedInstance].userInfo.uid),
//                           @"access_token" : [KABModel sharedInstance].userInfo.access_token};
//    [[XDAFNetworking sharedInstance] GET:[ApiManager apiExhibitionBuyableNoti] parameters:pars progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
//        NSLog(@"请求Noti返回：%@", responseObject);
//        if ([responseObject[KABGlobalJsonKeyErrCode] integerValue] == 200) {
//            self.is_notified = [responseObject[KABGlobalJsonKeyResult][@"is_notified"] boolValue];
//            [self refreshWholeView];
//        } else {
//            [MBProgressHUD showPromptWithAutoHideInView:self.view message:responseObject[KABGlobalJsonKeyMsg]];
//        }
//    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
//        NSLog(@"请求Noti点赞失败：%@", error);
//        [MBProgressHUD showPromptWithAutoHideInView:self.view message:@"网络请求失败"];
//    }];
//}

- (void)requestSetJpushNotifyWithIndex:(NSInteger)index is_notified:(BOOL)is_notified {
    // 必须要登录
    if (![KABModel sharedInstance].isLogin) {
        [[NSNotificationCenter defaultCenter] postNotificationName:KABGlobalNotiUserTokenInvalid object:nil];
        return;
    }
    
    // 开关请求
    NSDictionary *pars = @{@"user_id" : @([KABModel sharedInstance].userInfo.uid),
                           @"access_token" : [KABModel sharedInstance].userInfo.access_token,
                           @"notify_type" : @(index + 1),
                           @"is_notified" : (is_notified ? @(1) : @(0))};
    [[XDAFNetworking sharedInstance] PUT:[ApiManager apiMineJpushNotify] parameters:pars success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        NSLog(@"请求Noti返回：%@", responseObject);
        if ([responseObject[KABGlobalJsonKeyErrCode] integerValue] == 200) {
            ;
        } else {
            [self.pushModel setNotifyState:!is_notified WithIndex:index];
            [self refreshWholeView];
            [MBProgressHUD showPromptWithAutoHideInView:self.view message:responseObject[KABGlobalJsonKeyMsg]];
        }
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        NSLog(@"请求Noti点赞失败：%@", error);
        [self.pushModel setNotifyState:!is_notified WithIndex:index];
        [MBProgressHUD showPromptWithAutoHideInView:self.view message:@"网络请求失败"];
        [self refreshWholeView];
    }];
}

- (void)requestGetJpushNotify {
    // 必须要登录
    if (![KABModel sharedInstance].isLogin) {
        [[NSNotificationCenter defaultCenter] postNotificationName:KABGlobalNotiUserTokenInvalid object:nil];
        return;
    }
    
    // 点赞请求
    NSDictionary *pars = @{@"user_id" : @([KABModel sharedInstance].userInfo.uid),
                           @"access_token" : [KABModel sharedInstance].userInfo.access_token};
    [[XDAFNetworking sharedInstance] GET:[ApiManager apiMineJpushNotify] parameters:pars progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        NSLog(@"请求Noti返回：%@", responseObject);
        if ([responseObject[KABGlobalJsonKeyErrCode] integerValue] == 200) {
            self.pushModel = [KABMineSettingPushModel yy_modelWithDictionary:responseObject[KABGlobalJsonKeyResult]];
            [self refreshWholeView];
        } else {
            [MBProgressHUD showPromptWithAutoHideInView:self.view message:responseObject[KABGlobalJsonKeyMsg]];
        }
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        NSLog(@"请求Noti点赞失败：%@", error);
        [MBProgressHUD showPromptWithAutoHideInView:self.view message:@"网络请求失败"];
    }];
}

#pragma mark - getters and setters
- (NSArray *)sectionTitleArray {
    if (!_sectionTitleArray) {
        _sectionTitleArray = @[@"通用", @"推送通知", @"关于Kabu咔咘", @""];
    }
    return _sectionTitleArray;
}
- (NSArray *)generalArray {
    if (!_generalArray) {
        if ([KABModel sharedInstance].userInfo.login_method == 0) {
            _generalArray = @[@"收货地址", @"修改密码", @"清理缓存"];
        } else if ([KABModel sharedInstance].userInfo.login_method == 1) {
            _generalArray = @[@"收货地址", @"绑定手机", @"清理缓存"];
        } else {
            _generalArray = @[];
        }
    }
    return _generalArray;
}
- (NSArray *)notifyArray {
    if (!_notifyArray) {
        _notifyArray = @[@"漫展提醒", @"关注动态提醒", @"评论通知"];
    }
    return _notifyArray;
}

- (NSArray *)aboutArray {
    if (!_aboutArray) {
//        _aboutArray = @[@"给我评价", @"版权信息", @"软件许可使用协议", @"特别声明"];
        _aboutArray = @[@"给我评价"];
    }
    return _aboutArray;
}

@end
